package com.xiang.utils;

import com.xiang.config.EsConfig;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 复合查询
 *
 * @author xiangtianlei@gogpay.cn
 * @date 2023-01-30
 */
public class BoolQuery {
    RestHighLevelClient client = EsConfig.getClient();
    Logger logger = LoggerFactory.getLogger(CreateDoc.class);

    /**
     * bool查询
     */
    @Test
    public void boolQuery() throws IOException {
        // 创建搜索request
        SearchRequest request = new SearchRequest(EsConfig.INDEX_NAME);
        // 封装bool
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.from(0);
        builder.size(20);
        BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
        queryBuilder.should(QueryBuilders.matchQuery("address", "云南"));
        queryBuilder.mustNot(QueryBuilders.termQuery("name", "谢恨割"));
        queryBuilder.must(QueryBuilders.termQuery("sex", "女"));
        queryBuilder.must(QueryBuilders.rangeQuery("age").lte(50));
        // 封装到query中
        builder.query(queryBuilder);
        //  封装到request中
        request.source(builder);
        // 请求
        SearchResponse res = client.search(request, RequestOptions.DEFAULT);
        TotalHits totalHits = res.getHits().getTotalHits();
        String s = totalHits.toString();
        logger.info("查询DSL:{}", request.source().toString());
        logger.info("查询的数据一共有：{}条", res.getHits().getHits().length);
        logger.info("查询结果：{}", s);
    }
}
